package com.apkcore.core.util.timetick

import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.util.Log
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.apkcore.core.receiver.TimeTickReceiver
import com.apkcore.core.util.SPUtils
import java.util.Calendar
import kotlin.math.abs

class TimeTickScheduler private constructor() {
    companion object {
        val instance: TimeTickScheduler by lazy { TimeTickScheduler() }
    }

    private val tasks = mutableListOf<TimeTickTask>()

    fun addTask(taskId: String, hour: Int, minute: Int, task: (context: Context) -> Unit) {
        val index = tasks.indexOfFirst { it.taskId == taskId }
        if (index != -1) {
            val existingTask = tasks[index]
            val updatedTask = existingTask.copy(hour = hour, minute = minute, task = task)
            tasks[index] = updatedTask
        } else {
            val timeTickTask = TimeTickTask(taskId, hour, minute, task)
            tasks.add(timeTickTask)
        }
        SPUtils.getInstance().save(taskId, -1)
    }

    private fun release() {
        tasks.clear()
    }

    fun executeTasksIfNeeded(context: Context) {
        val currentTimeMillis = System.currentTimeMillis()
        val currentDay = Calendar.getInstance().get(Calendar.DAY_OF_YEAR)

        val calendar = Calendar.getInstance()
        tasks.forEach { timeTickTask ->
            val taskTime = calendar.apply {
                set(Calendar.HOUR_OF_DAY, timeTickTask.hour)
                set(Calendar.MINUTE, timeTickTask.minute)
                set(Calendar.SECOND, 0)
                set(Calendar.MILLISECOND, 0)
            }.timeInMillis

            // 检查当前时间是否在目标时间的前后1分钟内
            if (currentTimeMillis - taskTime < 60000 && currentTimeMillis > taskTime) {
//            if (abs(currentTimeMillis - taskTime) < 60000) {
                val lastExecutionDay = SPUtils.getInstance().getInt(timeTickTask.taskId, -1)
                // 如果任务尚未在今天执行过
                if (lastExecutionDay != currentDay) {
                    timeTickTask.task.invoke(context)
                    // 更新任务的最后执行时间为今天
                    SPUtils.getInstance().save(timeTickTask.taskId, currentDay)
                }
            }
        }
    }

    private val timeTickReceiver by lazy { TimeTickReceiver(instance) }

    fun register(context: Context) {
        if (context is LifecycleOwner) {
            Log.d(TAG, "register: is LifecycleOwner")
            context.lifecycle.addObserver(object : DefaultLifecycleObserver {
                override fun onDestroy(owner: LifecycleOwner) {
                    unregister(context)
                    super.onDestroy(owner)
                }
            })
        }
        val filter = IntentFilter(Intent.ACTION_TIME_TICK)
        context.registerReceiver(timeTickReceiver, filter)
    }

    fun unregister(context: Context) {
        release()
        context.unregisterReceiver(timeTickReceiver)
    }

    private val TAG = "TimeTickScheduler"
}

data class TimeTickTask(
    val taskId: String, // 唯一标识符
    val hour: Int,
    val minute: Int,
    val task: (context: Context) -> Unit
)